package org.example.controller;

import com.alipay.remoting.exception.CodecException;
import org.checkerframework.checker.units.qual.A;
import org.example.command.OrderCmd;
import org.example.order.CmdType;
import org.example.order.OrderDirection;
import org.example.order.OrderType;
import org.example.service.GatewayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.client.RestClientTest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.atomic.AtomicLong;

@RestController
public class StockController {

    AtomicLong id = new AtomicLong(0);

    @Autowired
    GatewayService gatewayService;

    @GetMapping("/buy/{code}/{price}/{volume}")
    public String buy(@PathVariable int code, @PathVariable long price, @PathVariable long volume) throws CodecException {
        OrderCmd order = createOrder(code, price, volume,OrderDirection.BUY);
        gatewayService.submitOrder(order);
        return "ok";
    }

    @GetMapping("/sell/{code}/{price}/{volume}")
    public String sell(@PathVariable int code, @PathVariable long price, @PathVariable long volume) throws CodecException {
        OrderCmd order = createOrder(code, price, volume,OrderDirection.SELL);
        gatewayService.submitOrder(order);
        return "ok";
    }

    public OrderCmd createOrder(int code,long price,long volume, OrderDirection direction) {
        OrderCmd orderCmd = new OrderCmd();
        orderCmd.setTimestamp(System.currentTimeMillis());
        orderCmd.setCode(code);
        orderCmd.setPrice(price);
        orderCmd.setVolumn(volume);
        orderCmd.setDirection(direction);
        orderCmd.setOid(id.addAndGet(1));

        orderCmd.setType(CmdType.NEW_ORDER);
        orderCmd.setMid(1);
        orderCmd.setOrderType(OrderType.LIMIT);
        return orderCmd;
    }
}
